package com.czl.module_storehouse.activity.supplier.add;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;

import com.czl.base.util.SpHelper;
import com.czl.module_base.activity.BaseActivity;
import com.czl.module_base.bean.CompanyBean;
import com.czl.module_base.bean.ListBean;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.mvp.view.SimpleView;
import com.czl.module_base.utils.RxRegUtils;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.bean.AddSupplierBean;
import com.czl.module_storehouse.bean.CityBean;
import com.czl.module_storehouse.bean.DistrictBean;
import com.czl.module_storehouse.bean.ProvinceBean;
import com.czl.module_storehouse.databinding.ActivitySupplierAddBinding;
import com.czl.module_storehouse.event.CompanyBeanEvent;
import com.czl.module_storehouse.event.SupplierEvent;
import com.czl.module_storehouse.mvp.presenter.SupplierPresenter;
import com.czl.module_storehouse.widget.picker.CityConfig;
import com.czl.module_storehouse.widget.picker.CityPicker;
import com.czl.module_storehouse.widget.picker.Interface.OnCityItemClickListener;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;


/**
 * @author xubin
 */
public class SupplierAddActivity extends BaseActivity<ActivitySupplierAddBinding> implements SimpleView {

    private final AddSupplierBean mAddSupplierBean = new AddSupplierBean();
    private CityPicker mCityPicker;
    private CompanyBean mCompanyBean;

    @InjectPresenter
    SupplierPresenter mSupplierPresenter;

    @Override
    protected ActivitySupplierAddBinding getBinding(LayoutInflater layoutInflater) {
        return ActivitySupplierAddBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mToolBinding.toolbarContentTitle.setText("添加供应商");
        binding.tvAddress.setOnClickListener(v -> selectCity());
        binding.btnCommit.setOnClickListener(v -> submit());
        EventBus.getDefault().register(this);
        if (mCompanyBean != null) {
            mAddSupplierBean.setEditable(true);
            mToolBinding.toolbarContentTitle.setText("编辑供应商");
            if (mSupplierPresenter != null) {
                mSupplierPresenter.selectByCompanyId(mCompanyBean.getCompanyId());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(CompanyBeanEvent event) {
        mCompanyBean = event.getCompanyBean();
    }

    private void setupView(CompanyBean companyBean) {
        if (companyBean == null) {
            return;
        }
        mAddSupplierBean.setEditable(true);
        mAddSupplierBean.setCompanyBean(companyBean,
                SpHelper.INSTANCE.decodeInt(Constants.SpKey.MANAGE_COMPANY_ID),
                SpHelper.INSTANCE.decodeString(Constants.SpKey.STOREHOUSE_USER_ID));
        binding.etCompany.setText(companyBean.getCompanyName());
        binding.etContact.setText(companyBean.getContactName());
        binding.etPhone.setText(companyBean.getContactPhone());
        binding.etInfoAddress.setText(companyBean.getCompanyAddress());
        binding.tvAddress.setText(companyBean.getCompanyName());
        String companyProvinceName = companyBean.getCompanyProvinceName();
        if (TextUtils.isEmpty(companyProvinceName)) {
            companyProvinceName = "";
        }
        String companyCityName = companyBean.getCompanyCityName();
        if (TextUtils.isEmpty(companyCityName)) {
            companyCityName = "";
        }
        String companyDistrictName = companyBean.getCompanyDistrictName();
        if (TextUtils.isEmpty(companyDistrictName)) {
            companyDistrictName = "";
        }
        String address = companyProvinceName + companyCityName + companyDistrictName;
        if (TextUtils.isEmpty(address)) {
            address = "选择城市";
        }
        binding.tvAddress.setText(address);
    }

    private void selectProvince() {
        if (mSupplierPresenter != null) {
            mSupplierPresenter.selectProvince();
        }
    }

    private void selectCity() {
        mCityPicker = new CityPicker();
        CityConfig cityConfig = new CityConfig.Builder().build();
        cityConfig.setShowType(CityConfig.ShowType.PRO_CITY_DIS);
        cityConfig.setDataStyle(CityConfig.DATA_ONLINE);
        mCityPicker.init(this, null);
        mCityPicker.setConfig(cityConfig);
        mCityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                String address;
                if (province == null) {
                    return;
                }
                mAddSupplierBean.setCompanyProvince(province.getProvinceCode());
                address = province.getName();
                if (city != null) {
                    mAddSupplierBean.setCompanyCity(city.getCityCode());
                    address += city.getName();
                } else {
                    mAddSupplierBean.setCompanyCity("");
                }
                if (district != null) {
                    mAddSupplierBean.setCompanyDistrict(district.getDistrictCode());
                    address += district.getName();
                } else {
                    mAddSupplierBean.setCompanyDistrict("");
                }
                binding.tvAddress.setText(address);
            }

            @Override
            public void onCancel() {
            }
        });
        mCityPicker.showCityPicker((requestType, code) -> {
            if (CityPicker.REQUEST_TYPE_PROVINCE == requestType) {
                selectProvince();
            } else if (CityPicker.REQUEST_TYPE_CITY == requestType) {
                //请求城市
                selectCity(code);
            } else {
                selectDistrict(code);
            }
        });
    }

    /**
     * 请求城市数据
     *
     * @param code
     */
    private void selectCity(String code) {
        if (mSupplierPresenter != null) {
            mSupplierPresenter.selectCity(code);
        }
    }

    /**
     * 请求县区
     *
     * @param code
     */
    private void selectDistrict(String code) {
        if (mSupplierPresenter != null) {
            mSupplierPresenter.selectDistrict(code);
        }
    }

    private void submit() {
        String companyName = binding.etCompany.getText().toString();
        if (TextUtils.isEmpty(companyName)) {
            showToast("请填写公司名称");
            return;
        }
        mAddSupplierBean.setCompanyName(companyName);
        String contactName = binding.etContact.getText().toString();
        if (TextUtils.isEmpty(contactName)) {
            showToast("请填写联系人名称");
            return;
        }
        mAddSupplierBean.setContactName(contactName);
        String contactPhone = binding.etPhone.getText().toString();
        if (TextUtils.isEmpty(contactPhone)) {
            showToast("请填写联系人电话");
            return;
        }
        if (!RxRegUtils.isMobileExact(contactPhone)) {
            showToast("请填写正确的电话号码");
            return;
        }
        mAddSupplierBean.setContactPhone(contactPhone);
//        String companyProvince = mAddSupplierBean.getCompanyProvince();
//        if (TextUtils.isEmpty(companyProvince)) {
//            showToast("请填写公司所在省份");
//            return;
//        }
//        String companyCity = mAddSupplierBean.getCompanyCity();
//        if (TextUtils.isEmpty(companyCity)) {
//            showToast("请填写公司所在城市");
//            return;
//        }
//        String companyDistrict = mAddSupplierBean.getCompanyDistrict();
//        if (TextUtils.isEmpty(companyCity)) {
//            showToast("请填写公司所在县区");
//            return;
//        }
        String companyAddress = binding.etInfoAddress.getText().toString();
//        if (TextUtils.isEmpty(companyAddress)) {
//            showToast("请填写公司详细地址");
//            return;
//        }
        mAddSupplierBean.setCompanyAddress(companyAddress);
        if (mSupplierPresenter != null) {
            if (mAddSupplierBean.isEditable()) {
                mSupplierPresenter.updateCompany(mAddSupplierBean, mCompanyBean);
            } else {
                mSupplierPresenter.addCompany(mAddSupplierBean);
            }
        }
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        switch (httpResponse.getRequestTag()) {
            case SupplierPresenter.TAG_SUPPLIER_UPDATE:
                showToast("更新成功");
                LiveEventBus.get(SupplierEvent.class).post(new SupplierEvent());
                finish();
                break;
            case SupplierPresenter.TAG_SUPPLIER_ADD:
                showToast("添加成功");
                LiveEventBus.get(SupplierEvent.class).post(new SupplierEvent());
                finish();
                break;
            case SupplierPresenter.TAG_PROVINCE:
                getProvince(httpResponse);
                break;
            case SupplierPresenter.TAG_CITY:
                getCity(httpResponse);
                break;
            case SupplierPresenter.TAG_DISTRICT:
                getDistrict(httpResponse);
                break;
            case SupplierPresenter.TAG_COMPANY_INFO:
                getCompanyInfo(httpResponse);
                break;
            default:
                break;
        }
    }

    private <T> void getProvince(HttpResponse<T> httpResponse) {
        //选择省份
        if (HttpResponse.FAILED == httpResponse.getState()) {
            if (mCityPicker != null) {
                mCityPicker.setViewState(CityPicker.VIEW_STATE_ERROR);
            }
            return;
        }
        Object data = httpResponse.getData();
        if (data == null) {
            return;
        }
        List<ProvinceBean> provinceBeans = null;
        if (data instanceof ListBean) {
            provinceBeans = ((ListBean<ProvinceBean>) data).getList();
        }
        if (mCityPicker != null) {
            mCityPicker.setProvinceListData(provinceBeans);
        }
    }

    private <T> void getCity(HttpResponse<T> httpResponse) {
        if (HttpResponse.FAILED == httpResponse.getState()) {
            if (mCityPicker != null) {
                mCityPicker.setViewState(CityPicker.VIEW_STATE_ERROR);
            }
            return;
        }
        Object data = httpResponse.getData();
        if (data == null) {
            return;
        }
        List<CityBean> cityBeans = null;
        if (data instanceof ListBean) {
            cityBeans = ((ListBean<CityBean>) data).getList();
        }
        if (mCityPicker != null) {
            mCityPicker.setCityListData(cityBeans);
        }
    }

    private <T> void getDistrict(HttpResponse<T> httpResponse) {
        if (HttpResponse.FAILED == httpResponse.getState()) {
            if (mCityPicker != null) {
                mCityPicker.setViewState(CityPicker.VIEW_STATE_ERROR);
            }
            return;
        }
        Object data = httpResponse.getData();
        if (data == null) {
            return;
        }
        List<DistrictBean> districtBeans = null;
        if (data instanceof ListBean) {
            districtBeans = ((ListBean<DistrictBean>) data).getList();
        }
        if (mCityPicker != null) {
            mCityPicker.setDistrictListData(districtBeans);
        }
    }

    private <T> void getCompanyInfo(HttpResponse<T> httpResponse) {
        Object data = httpResponse.getData();
        if (data == null) {
            return;
        }
        if (data instanceof CompanyBean) {
            setupView((CompanyBean) data);
        }
    }
}
